package com.atguigu.gulimall.order.web;

import com.atguigu.common.exception.NoStockException;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.OrderConfimVo;
import com.atguigu.gulimall.order.vo.OrderSubmitVo;
import com.atguigu.gulimall.order.vo.SubmitOrderResponesVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {
    final
    OrderService orderService;

    public OrderWebController(OrderService orderService) {
        this.orderService = orderService;
    }

    @GetMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfimVo confimVo = orderService.confirmOrder();
        model.addAttribute("orderConfirmData", confimVo);
        return "confirm";
    }

    /**
     * 提交下单功能
     *
     * @param vo
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo vo, Model model, RedirectAttributes redirectAttributes) {

        //下单成功来到支付选择页
        //下单失败回到订单确认页重新确认订单
        try {
            SubmitOrderResponesVo responesVo = orderService.submitOrder(vo);
            if (responesVo.getCode() == 0) {
                model.addAttribute("submitOrderResp", responesVo);
                return "pay";
            } else {
                String msg = "购买失败，";
                switch (responesVo.getCode()) {
                    case 1:
                        msg += "订单信息过期，请刷新再次提交";
                        break;
                    case 2:
                        msg += "订单商品价格发生变化，请确认后再次提交";
                        break;
                    case 3:
                        msg += "该商品已售完";
                        break;
                }
                //如果下单失败就可以回到下单确认页，让用户重新确认下订单信息
                redirectAttributes.addFlashAttribute("msg", msg);
                return "redirect:http://order.gulimall.com/toTrade";
            }
        } catch (NoStockException e) {
            redirectAttributes.addFlashAttribute("msg", e.getMessage());
            return "redirect:http://order.gulimall.com/toTrade";
        }

    }
}
